<template>
  <div>
    <div :style="{
      height: size,
      width: size
    }" class="page-item page-add" @click="onClickAdd"></div>
  </div>
</template>

<script lang="ts" >
import { defineComponent } from "vue";
export default defineComponent({
  name: "UploadAdd",
});
</script>

<script lang="ts" setup>
import { withDefaults, reactive, ref, onBeforeUnmount } from "vue";
import { request } from "@/utils/axios";
import { uploadFile } from "@/utils/api";

let props = withDefaults(defineProps<{
  /**
   * 大小
   */
  size?: string
  /**
   * 是否启动多文件上传
   */
  multiple?: boolean;

  /**
   * 上传文件选择的类型
   */
  accept?: string;

  /**
   * 业务参数
   */
  docType: string;

  /**
   * 是为为图片, 图片的时候默认进行图片压缩
   */
  isImage?: boolean;

  /**
   * 在上传之前
   * 可以通过返回Promise.reject状态 来阻止上传
   */
  beforeUpload?: (file: File, files: File[]) => Promise<void>
}>(), {
  size: "148px",
  multiple: false,
  accept: "",
  isImage: false,
  beforeUpload: () => Promise.resolve()
})

let emit = defineEmits<{
  (e: "uploadSuccess", para: {
    /**
     * 文件名称
     */
    fileName: string;

    /**
     * 文件全链接
     */
    fileUrl: string;
  }, file: File): void;
  (e: "uploadError", file: File): void;
}>()

/**
 * 点击新增
 */
function onClickAdd() {
  let inputDom = document.createElement("input");
  inputDom.type = "file";
  inputDom.style.display = "none";
  //添加多文件上传
  if (props.multiple) {
    inputDom.multiple = true;
  }
  if (props.accept) {
    inputDom.accept = props.accept;
  }

  document.body.append(inputDom);

  //获取file文件
  inputDom.onchange = e => {
    if (inputDom.files && inputDom.files.length > 0) {
      let fileList: File[] = [];
      //首先将 FIleList 格式文件 转化成 File[]
      for (let i = 0; i < inputDom.files.length; i++) {
        fileList.push(inputDom.files.item(i)!);
      }
      for (let item of fileList) {
        props.beforeUpload(item, fileList)
          .then(() => {
            //运行文件上传功能
            upload(item);
          })
          .catch(() => {
          });
      }
    }
    //删除组件
    inputDom.remove();
  };
  inputDom.click();
}


/**
 * 文件上传
 * 可用于外部调用
 */
function upload(file: File,) {
  uploadFile(file, props.docType, {
    isImage: props.isImage
  })
    .then((res) => {
      emit("uploadSuccess", {
        fileName: res.fileName,
        fileUrl: res.fileUrl
      }, file);
    })
    .catch(() => {
      emit("uploadError", file)
    })
}

defineExpose({
  upload
})

</script>

<style lang="less" scoped>
@import url(../main.less);

.x_x-uploadadd-icon {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;

  .x_x-uploadadd-icon-l {
    width: 40%;
    height: 3px;
    background-color: rgba(0, 0, 0, 0.2);
    border-radius: 10px;
  }

  &::before {
    content: "";
    .x_x-uploadadd-icon-l;
  }

  &::after {
    content: "";
    .x_x-uploadadd-icon-l;
    position: absolute;
    transform: rotate(90deg);
  }
}
</style>